﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing.Drawing2D;
using System.Collections.ObjectModel;
using MyWebPagesStarterKit.Controls;
using System.Collections.Specialized;

public partial class Administration_UIControls_ImageTool : System.Web.UI.UserControl
{

   

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            CreateImageList();
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        originalImage.ImageUrl = this.Url;
    }

    protected string Url
    {
        get
        {
            originalImage.Visible = true;
            return (string)ViewState["ImageUrl"];
        }
        set { ViewState["ImageUrl"] = value; }
    }

    protected void Action(object sender, CommandEventArgs e)
    {
        originalImage.Visible = true;
        System.Drawing.Image image = System.Drawing.Image.FromFile(e.CommandName);
        tmpPath.Value = e.CommandName;
        this.Url = "~/Administration/Resources/css/crop/ImageProvider.ashx?image=" + CreatePath("app_data", e.CommandName);
        originalImage.ImageUrl = "~/Administration/Resources/css/crop/ImageProvider.ashx?image=" + CreatePath("app_data", e.CommandName);
        ssize.Text = "" + image.Width + "x" + image.Height;
    }


    private void CreateImageList()
    {
        string path = Server.MapPath("~/App_Data/UserImages/Image");

        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        string[] dirs = Directory.GetDirectories(path);
        int id = 0;

        List<ImageB> list = new List<ImageB>();

        foreach (string folder in dirs)
        {
            foreach (string file in Directory.GetFiles(folder))
            {
                ImageB img = new ImageB();
                img.ToolTip = Path.GetFileName(file);
                img.ImageUrl = string.Format("~/ImageHandler.ashx?image={0}&height={1}&width={2}&mapped=false", CreatePath("app_data", file), 90, 90);
                img.ID = "GalleryButton_" + id;
                img.ImagePath = file;
                id += 1;
                img.CommandName = file;
                list.Add(img);
            }
        }

        rptImages.DataSource = list;
        rptImages.DataBind();
    }

    public class ImageB : ImageButton
    {
        private string _ImagePath;

        public string ImagePath
        {
            get { return _ImagePath; }
            set { _ImagePath = value; }
        }
    }


    public string CreatePath(string root, string spath)
    {
        string path = spath.ToLower();
        try
        {
            int first = path.LastIndexOf(root);
            path = "~/" + path.Substring(first);
            char c = Path.DirectorySeparatorChar;
            path = path.Replace(c, '/');
        }
        catch { }
        return path;
    }



    protected void ResizeImage(object sender, EventArgs e)
    {
        try
        {
            if (!originalImage.Visible)
                return;

            string p = originalImage.ImageUrl.Substring(originalImage.ImageUrl.LastIndexOf("/") + 1);
            string img = Server.MapPath("~/App_Data/UserImages/Image/tmp/" + p);

            using (Stream imgStream = File.Open(img, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                int width = 0;
                if (!string.IsNullOrEmpty(txtWidth.Text))
                    width = Convert.ToInt32(txtWidth.Text);

                int height = 0;
                if (!string.IsNullOrEmpty(txtHeight.Text))
                    height = Convert.ToInt32(txtHeight.Text);

                System.Drawing.Image pixels = System.Drawing.Image.FromFile(img);
                int w = pixels.Width;
                int h = pixels.Height;

                if (width == 0)
                    width = w;
                if (height == 0)
                    height = h;

                Size c = GenerateImageDimensions(w, h, width, height);
                ssize.Text = "" + c.Width + "x" + c.Height;

                Bitmap b = resize(imgStream, c.Width, c.Height);
                string ext = Path.GetExtension(img);

                using (EncoderParameters encoderParameters = new EncoderParameters(1))
                {
                    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

                    string k = string.Format("{0}{1}x{2}{3}", img.Replace(ext, ""), b.Width, b.Height, ext);

                    b.Save(string.Format("{0}{1}x{2}{3}", img.Replace(ext, ""), b.Width, b.Height, ext), GetImageCodec(ext), encoderParameters);

                    System.Drawing.Image o = System.Drawing.Image.FromFile(Server.MapPath("~/app_Data/UserImages/image/tmp/" + Path.GetFileName(k)));
                    originalImage.Width = o.Width;
                    originalImage.Height = o.Height;
                    originalImage.ImageUrl = "~/Administration/Resources/css/crop/ImageProvider.ashx?mapped=false&image=~/app_Data/UserImages/image/tmp/" + Path.GetFileName(k);
                }

                b.Dispose();
            }
        }
        catch { }

    }

    public Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
    {
        double multiplier = 0;
        string layout;

        if (currH > currW)
            layout = "portrait";
        else
            layout = "landscape";

        switch (layout.ToLower())
        {
            case "portrait":
                //calculate multiplier on heights
                if (destH > destW)
                {
                    multiplier = (double)destW / (double)currW;
                }
                else
                {
                    multiplier = (double)destH / (double)currH;
                }
                break;
            case "landscape":
                //calculate multiplier on widths
                if (destH > destW)
                {
                    multiplier = (double)destW / (double)currW;
                }
                else
                {
                    multiplier = (double)destH / (double)currH;
                }
                break;
        }
        return new Size((int)(currW * multiplier), (int)(currH * multiplier));
    }


    private Bitmap resize(Stream SourceImage, int MaxWidth, int MaxHeight)
    {
        Bitmap b = null;

        using (System.Drawing.Image i = System.Drawing.Image.FromStream(SourceImage))
        {
            b = new Bitmap(MaxWidth, MaxHeight);

            using (Graphics g = Graphics.FromImage(b))
            {
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(i, new Rectangle(0, 0, MaxWidth, MaxHeight));
                g.Save();
            }
        }
        return b;
    }


    protected void LoadImage(object sender, EventArgs e)
    {
        try
        {
            if (fileupload.HasFile)
            {
                try
                {
                    string[] files = Directory.GetFiles(Server.MapPath("~/App_Data/UserImages/Image/tmp/cropped/"));
                    foreach (string file in files)
                        File.Delete(file);
                }
                catch { }

                string path = "~/Administration/Resources/css/crop/ImageProvider.ashx?mapped=false&image=~/app_Data/UserImages/image/tmp/" + Path.GetFileName(fileupload.FileName);
                string imagepath = Server.MapPath("~/App_Data/UserImages/image/tmp/" + Path.GetFileName(fileupload.FileName));
                fileupload.SaveAs(imagepath);

                System.Drawing.Image img = System.Drawing.Image.FromFile(imagepath);
                originalImage.Width = img.Width;
                originalImage.Height = img.Height;
                originalImage.ImageUrl = path;
                originalImage.Visible = true;
                ssize.Text = "" + img.Width + "x" + img.Height;
                imgCropped.Visible = false;
                tmpPath.Value = imagepath;
            }
            else
            {
                originalImage.Visible = false;
                imgCropped.Visible = false;
            }
        }
        catch { }
    }

    protected void btnCrop_Click(object sender, EventArgs e)
    {

        string tmppath = Server.MapPath("~/App_Data/UserImages/Image/tmp/");
        if (!Directory.Exists(tmppath))
            Directory.CreateDirectory(tmppath);

        tmppath = string.Concat(tmppath, "cropped");
        if (!Directory.Exists(tmppath))
            Directory.CreateDirectory(tmppath);

       
            int X1 = Convert.ToInt32(Request.Form["x1"]);
            int Y1 = Convert.ToInt32(Request["y1"]);
            int X2 = Convert.ToInt32(Request.Form["x2"]);
            int Y2 = Convert.ToInt32(Request.Form["y2"]);
            int X = System.Math.Min(X1, X2);
            int Y = System.Math.Min(Y1, Y2);
            int w = Convert.ToInt32(Request.Form["w"]);
            int h = Convert.ToInt32(Request.Form["h"]);

            // There can be any image type (jpg,jpeg,png,gif) from any location on server
            string p = originalImage.ImageUrl.Substring(originalImage.ImageUrl.LastIndexOf("/") + 1);
            string originalFile = Server.MapPath("~/App_Data/UserImages/Image/tmp/" + p);

            if (!File.Exists(p))
                originalFile = tmpPath.Value;

        
            //strFileNamePrefix = Regex.Replace(strFileNamePrefix, @"[\\/\?\:\<\>\|\*]", "_");

            using (System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile))
            {
                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);

                    Graphics _graphic = null;
                    using (_graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        _graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);
                    }
                    
                    string extension = Path.GetExtension(originalFile);
                    string croppedFileName = Guid.NewGuid().ToString();
                    string path = Server.MapPath("~/app_Data/UserImages/image/tmp/cropped/");

                    // If the image is a gif file, change it into png
                    if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                    {
                        extension = ".png";
                    }

                    string newFullPathName = string.Concat(path, croppedFileName, extension);

                    using (EncoderParameters encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                        System.Drawing.Image b = (Bitmap)_bitmap.Clone(); //.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                        b.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                    }
             
                    imgCropped.Visible = true;
                    imgCropped.ImageUrl = "~/Administration/Resources/css/crop/ImageProvider.ashx?mapped=false&image=~/app_Data/UserImages/image/tmp/cropped/" + croppedFileName + extension;
                    
                }
                
            }
       
    }

    /// <summary>
    /// Find the right codec
    /// </summary>
    /// <param name="extension"></param>
    /// <returns></returns>
    public static ImageCodecInfo GetImageCodec(string extension)
    {
        extension = extension.ToUpperInvariant();
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
        foreach (ImageCodecInfo codec in codecs)
        {
            if (codec.FilenameExtension.Contains(extension))
            {
                return codec;
            }
        }
        return codecs[1];
    }
}
